import 'package:flutter/cupertino.dart';
import 'package:get/get.dart';
import 'package:nyh_motorcade_app/entity/cash_flow_entity.dart';
import 'package:nyh_motorcade_app/http/http_address.dart';
import 'package:nyh_motorcade_app/http/http_manager.dart';
import 'package:nyh_motorcade_app/utils/date_utils.dart';
import 'package:nyh_motorcade_app/utils/sp_utils.dart';
import 'package:nyh_motorcade_app/utils/toast_utils.dart';
import 'package:nyh_motorcade_app/widgets/multi_state/multi_state_widget.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

class CashFlowController extends GetxController {
  RefreshController refreshController = RefreshController();
  MultiState multiState = MultiState.loading;
  ScrollController scrollController = ScrollController();

  //卡id或者车队id
  String sourceId = "";

  //账户类型
  //全部账户、公司账户、车队账户、卡账户
  String accountType = "";

  //交易类型
  //全部类型、公司付款1、公司收款2、金额拨入3、金额拨出4、订单支付5、订单作废6、充值7
  String transactionType = "";

  //开始时间
  late String startDate;

  //结束时间
  late String endDate;

  //选择近一周(默认)
  bool isSelectWeek = true;

  //选择近一月
  bool isSelectOneMonth = false;

  //选择近三月
  bool isSelectThreeMonth = false;

  //选择筛选
  bool isSelectFilter = false;

  //是否显示筛选框
  bool isShowFilterWidget = false;

  //页数
  int page = 1;

  List<CashFlowItem> cashFlowList = [];

  @override
  void onReady() {
    super.onReady();
    dynamic arguments = Get.arguments;
    if (arguments != null && arguments is Map) {
      sourceId = arguments["sourceId"];
      accountType = arguments["accountType"];
    }
    setSelectWeekDate();
    getCashFlow();
  }

  Future<void> onRefresh() async {
    page = 1;
    getCashFlow();
  }

  Future<void> onLoading() async {
    getCashFlow();
  }

  void onRetry() {
    multiState = MultiState.loading;
    update();
    getCashFlow();
  }

  Future<void> getCashFlow() async {
    httpManager.post(
      Get.context,
      HttpAddress.GET_CASH_FLOR,
      {
        "superId": await SPUtils.getString(SPUtils.COMPANY_ID),
        "sourceId": sourceId.isNotEmpty ? sourceId : null,
        "accountType": accountType.isNotEmpty ? accountType : null,
        "queryTradeType": transactionType.isNotEmpty ? transactionType : null,
        "startDate": startDate.isNotEmpty ? startDate + " 00:00:00" : null,
        "endDate": endDate.isNotEmpty ? endDate + " 23:59:59" : null,
      },
      headers: {"page": page, "limit": 10},
      isToast: true,
      onSuccess: (data) {
        if (data == null) {
          ToastUtils.toast("请求失败");
          if (refreshController.isRefresh) {
            refreshController.refreshFailed();
          } else {
            refreshController.loadFailed();
          }
          if (page == 1) {
            multiState = MultiState.fail;
          }
          update();
          return;
        }
        CashFlowEntity cashFlowEntity = CashFlowEntity().fromJson(data);
        List<CashFlowItem> list = cashFlowEntity.item ?? [];
        if (list.isNotEmpty) {
          multiState = MultiState.success;
          if (refreshController.isRefresh) {
            cashFlowList.clear();
            refreshController.refreshCompleted();
            if (scrollController.hasClients) {
              scrollController.jumpTo(0);
            }
          } else {
            if (list.length >= 10 || page == 1) {
              refreshController.loadComplete();
            } else {
              refreshController.loadNoData();
            }
          }
          if (page == 1) {
            cashFlowList.clear();
          }
          cashFlowList.addAll(list);
          page++;
        } else {
          if (refreshController.isRefresh) {
            refreshController.refreshCompleted();
          } else {
            refreshController.loadNoData();
          }
          if (page == 1) {
            multiState = MultiState.empty;
          }
        }
        update();
      },
      onFail: (code, msg) {
        if (refreshController.isRefresh) {
          refreshController.refreshFailed();
        } else {
          refreshController.loadFailed();
        }
        if (page == 1) {
          multiState = MultiState.fail;
        }
        update();
      },
      onError: (msg) {
        if (refreshController.isRefresh) {
          refreshController.refreshFailed();
        } else {
          refreshController.loadFailed();
        }
        if (page == 1) {
          multiState = MultiState.error;
        }
        update();
      },
    );
  }

  void selectWeek() {
    if (isSelectWeek) {
      return;
    }
    isSelectWeek = true;
    isSelectOneMonth = false;
    isSelectThreeMonth = false;
    isSelectFilter = false;
    isShowFilterWidget = false;
    setSelectWeekDate();
    if (sourceId.isEmpty) {
      accountType = "";
    }
    transactionType = "";
    page = 1;
    multiState = MultiState.loading;
    update();
    getCashFlow();
  }

  void selectOneMonth() {
    if (isSelectOneMonth) {
      return;
    }
    isSelectWeek = false;
    isSelectOneMonth = true;
    isSelectThreeMonth = false;
    isSelectFilter = false;
    isShowFilterWidget = false;
    setSelectOneMonthDate();
    if (sourceId.isEmpty) {
      accountType = "";
    }
    transactionType = "";
    page = 1;
    multiState = MultiState.loading;
    update();
    getCashFlow();
  }

  void selectThreeMonth() {
    if (isSelectThreeMonth) {
      return;
    }
    isSelectWeek = false;
    isSelectOneMonth = false;
    isSelectThreeMonth = true;
    isSelectFilter = false;
    isShowFilterWidget = false;
    setSelectThreeMonthDate();
    if (sourceId.isEmpty) {
      accountType = "";
    }
    transactionType = "";
    page = 1;
    multiState = MultiState.loading;
    update();
    getCashFlow();
  }

  void selectFilter(String startDate, String endDate, String accountType, String transactionType) {
    this.startDate = startDate;
    this.endDate = endDate;
    this.accountType = accountType;
    this.transactionType = transactionType;
    isSelectWeek = false;
    isSelectOneMonth = false;
    isSelectThreeMonth = false;
    isSelectFilter = true;
    page = 1;
    multiState = MultiState.loading;
    update();
    getCashFlow();
  }

  void setSelectWeekDate() {
    startDate = DateUtil.subtractDate(Duration(days: 6));
    endDate = DateUtil.getCurrentDate();
  }

  void setSelectOneMonthDate() {
    startDate = DateUtil.subtractDate(Duration(days: 30));
    endDate = DateUtil.getCurrentDate();
  }

  void setSelectThreeMonthDate() {
    startDate = DateUtil.subtractDate(Duration(days: 90));
    endDate = DateUtil.getCurrentDate();
  }
}

enum FilterType {
  week,
  oneMonth,
  threeMonth,
  filter,
}
